<template>
  <el-drawer v-model="visible" title="编辑文章" size="68vw">
    <el-form label-position="top" :rules="rules" :model="modelValue" ref="formRef">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="文章标题" prop="articleName">
            <el-input v-model="modelValue.articleName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="作者" prop="author">
                <el-input v-model="modelValue.author"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文章是否关闭" prop="off">
                <el-switch v-model="modelValue.off"></el-switch>
                <span class="tips">打开，文章将不会显示</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章分类" prop="category.id">
            <el-tree-select
              style="width: 100%"
              v-model="modelValue.category!.id"
              :data="categories"
              node-key="id"
              clearable
              :multiple="false"
              :props="{
                label: 'categoryName'
              }"
              :render-after-expand="false"
              check-on-click-node
            ></el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章副标题" prop="articleSubName">
            <el-input v-model="modelValue.articleSubName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="简介" prop="intro">
        <el-input type="textarea" v-model="modelValue.intro"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="context">
        <WangEditor v-model:value="modelValue.context"></WangEditor>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ArticleCategorySchema, ArticleSchema } from "@/schema";
import { nextTick, reactive, ref, watch } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { fetchArticleCategoryTrees } from "@/api/modules/article_category";
import { ResultEnum } from "@/enums/httpEnum";
import { ElMessage, FormInstance } from "element-plus";
import { editArticle, fetchArticleInfo, saveArticle } from "@/api/modules/article";
import { EmitProps } from "@/typings/interface";
import { isNotEmpty } from "@/utils/isHelper";

const visible = ref(false);
const formRef = ref<FormInstance>();
const categories = ref();
const modelValue = reactive<ArticleSchema>({
  articleName: "",
  articleSubName: "",
  author: "",
  intro: "",
  context: "",
  off: false,
  category: { id: "" } as ArticleCategorySchema
});
const emits = defineEmits<EmitProps>();

const rules = {
  articleName: { required: true, message: "请输入文章名称", trigger: "blur" },
  articleSubName: { required: true, message: "请输入文章副标题", trigger: "blur" },
  author: { required: true, message: "请输入文章作者", trigger: "blur" },
  intro: { required: true, message: "请输入文章简介", trigger: "blur" },
  context: { required: true, message: "请输入文章内容", trigger: "blur" },
  "category.id": { required: true, message: "请选择文章分类", trigger: "blur" }
};
function submit() {
  formRef.value?.validate().then(valid => {
    if (valid) {
      if (modelValue?.id) {
        edit();
      } else {
        save();
      }
    }
  });
}

function edit() {
  editArticle({ id: modelValue.id }, modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      emits("success");
      visible.value = false;
      ElMessage.success("编辑成功！");
    } else {
      ElMessage.error(message);
    }
  });
}

function save() {
  saveArticle(modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      emits("success");
      visible.value = false;
      ElMessage.success("编辑成功！");
    } else {
      ElMessage.error(message);
    }
  });
}

function fetchTrees() {
  fetchArticleCategoryTrees().then(r => {
    const { code, data, message } = r;
    if (code === ResultEnum.SUCCESS) {
      categories.value = data.list ?? [];
    } else {
      ElMessage.error(message);
    }
  });
}

watch(
  () => visible.value,
  newVal => {
    if (!newVal) {
      nextTick(() => {
        formRef.value?.resetFields();
        if (modelValue.category?.id) modelValue.category.id = "";
      });
    }
  }
);

defineExpose({
  open(row) {
    visible.value = true;
    fetchTrees();

    if (row?.id) {
      fetchArticleInfo({ id: row?.id }).then(r => {
        const { code, data, message } = r;
        if (code === ResultEnum.SUCCESS) {
          Object.assign(modelValue, {
            ...data,
            parent: isNotEmpty(data.category) ? data.category : { id: "" }
          });
        } else {
          ElMessage.error(message);
        }
      });
    }
  }
});
</script>

<style lang="scss" scoped>
.tips {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}
</style>
